﻿using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using UniMana.Data;
using UniMana.Utils.Data;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using UniMana.Utils.Configs;

namespace UniMana.Win.Leadership
{
    public partial class Frm_Score2_EditScoreCensorship : DevExpress.XtraEditors.XtraForm
    {
        private DataTable m_tblTable = new DataTable();
        private DBMain m_data = new DBMain();
        private int m_iLog_ScoreEditKey = 0;
        public DevExpress.Utils.WaitDialogForm dlg;

        private string m_strID;
        private int m_iClassKey;
        private int m_iScoreType;
        private double m_iOldScore;
        private double m_iNewScore;

        private Guid m_gStudentKey;
        private Guid m_gPerson;
        private DateTime m_dDateTime;

        private bool m_bPermitValue;
        private bool m_bRefuseValue;
        private bool m_bStatusValue;

        public Frm_Score2_EditScoreCensorship()
        {
            if (!SysUtils.CheckAccessByRule(RuleConfig.DPSD))
            {
                return;
            }
            InitializeComponent();
        }

        /// <summary>
        /// Lấy các phiếu
        /// </summary>

        private void LoadData()
        {
            m_tblTable = new DataTable();
            m_tblTable = (m_data.m_DCReadOnly.Log_ScoreEdits.GetAllData()).ToDataTable();
            gctView.DataSource = m_tblTable;
        }

        /// <summary>
        /// form load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void Frm_Score2_EditScoreCensorship_Load(object sender, EventArgs e)
        {            
            LoadData();
            rluTraining_ScoreType.GetData(m_data.m_DCReadOnly.Training_ScoreTypes, "Training_ScoreTypeKey", "Name");
            rluTraining_Student_Class.GetData(m_data.m_DCReadOnly.Training_Student_Classes, "Training_StudentKey", "ID");
            rluTraining_Subject_Class.GetData(m_data.m_DCReadOnly.Training_Subject_Classes, "Training_Subject_ClassKey", "ID");
        }

        /// <summary>
        /// Lấy thông tin chi tiết của 1 phiếu yêu cầu
        /// </summary>

        private void GetValues(int m_iLog_ScoreEditKey)
        {
            Log_ScoreEditInfo loginfo = new Log_ScoreEditInfo(m_iLog_ScoreEditKey);
            if (loginfo.Properties.Log_ScoreEditKey > 0)
            {
                m_strID = loginfo.Properties.ID.ToString();
                m_iClassKey = int.Parse(loginfo.Properties.Training_Subject_ClassKey.ToString());
                m_gStudentKey = Guid.Parse(loginfo.Properties.Training_StudentKey.ToString());
                m_iScoreType = int.Parse(loginfo.Properties.Training_ScoreTypeKey.ToString());
                m_gPerson = Guid.Parse(loginfo.Properties.RepuiredBy.ToString());
                m_dDateTime = (DateTime)(loginfo.Properties.CreateOn);
                try
                {
                    m_iOldScore = Convert.ToDouble(loginfo.Properties.OldScore.ToString());
                }
                catch { m_iOldScore = 0; }
                m_iNewScore = Convert.ToDouble(loginfo.Properties.NewScore.ToString());
                m_bStatusValue = (bool)(loginfo.Properties.Status);
            }
        }

        /// <summary>
        /// Hiển thị thông tin phiếu chọn
        /// </summary>

        private void ShowInfomation(int m_iLog_ScoreEditKey)
        {
            if (m_iLog_ScoreEditKey > 0)
            {
                GetValues(m_iLog_ScoreEditKey);
                Training_Subject_ClassInfo subclsinfo = new Training_Subject_ClassInfo(m_iClassKey);
                txtClassName.Text = subclsinfo.Properties.Name;
                Training_StudentInfo stdinfo = new Training_StudentInfo(m_gStudentKey.ToString());
                txtStudentName.Text = stdinfo.Properties.LastName + " " + stdinfo.Properties.SureName;
                Personnel_PersonnelInfo perinfo = new Personnel_PersonnelInfo(Guid.Parse(m_gPerson.ToString()));
                txtPersonName.Text = perinfo.Properties.LastName + " " + perinfo.Properties.Name;
                txtDatetime.Text = m_dDateTime.ToString();
                Log_ScoreEditInfo loginfo = new Log_ScoreEditInfo(m_iLog_ScoreEditKey);
                rtbReason.Text = loginfo.Properties.Reasons;
                if (loginfo.Properties.Feedback != null)
                {
                    rtbFeedback.Text = loginfo.Properties.Feedback;
                }
                else
                {
                    rtbFeedback.Text = "";
                }
                if (m_bStatusValue)
                {
                    rtbFeedback.Enabled = false;
                }
                else
                {
                    rtbFeedback.Enabled = true;
                }
            }
        }

        /// <summary>
        /// Tô màu các mã phiếu chưa duyệt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void grvView_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView View = sender as GridView;
            if (!View.IsFilterRow(e.RowHandle))
            {
                bool permit = Convert.ToBoolean(View.GetRowCellValue(e.RowHandle, View.Columns["Permit"]));
                bool refuse = Convert.ToBoolean(View.GetRowCellValue(e.RowHandle, View.Columns["Refuse"]));
                if ((permit == false) && (refuse == false))
                    e.Appearance.BackColor = Color.Silver;
            }
        }

        /// <summary>
        /// Theo dõi sự thay đổi trên lưới và xử lý các sự kiện
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void grvView_ShowingEditor(object sender, CancelEventArgs e)
        {
            if (this.grvView.FocusedColumn == gclPermit)
            {
                m_iLog_ScoreEditKey = int.Parse(this.grvView.GetRowCellValue(this.grvView.FocusedRowHandle, "Log_ScoreEditKey").ToString());
                ShowInfomation(m_iLog_ScoreEditKey);
                Log_ScoreEditInfo loginfo = new Log_ScoreEditInfo(m_iLog_ScoreEditKey);
                if (loginfo.Properties.Log_ScoreEditKey > 0)
                {
                    GetValues(m_iLog_ScoreEditKey);
                    if (loginfo.Properties.Status.Value == false)
                    {
                        DialogResult result = XtraMessageBox.Show("Bạn muốn phê duyệt phiếu " + m_strID, "Thông báo",MessageBoxButtons.YesNo);
                        if (result == DialogResult.Yes)
                        {
                            m_bPermitValue = (bool)this.grvView.GetFocusedRowCellValue(gclPermit);
                            this.grvView.SetFocusedRowCellValue(gclPermit, !m_bPermitValue);

                            // update
                            if (rtbFeedback.Text != "")
                                loginfo.Properties.Feedback = rtbFeedback.Text;

                            loginfo.Properties.Permit = true;
                            loginfo.Properties.Status = true;
                            loginfo.Properties.AccountCensorship = Utils.LoginInfo.GblLoginInfo.sysLoginUserKey;
                            loginfo.Properties.DateCensorship = SysDateTime.Now;
                            loginfo.Save();

                            Training_ScoreInfo scoreinfo = new Training_ScoreInfo(loginfo.Properties.Training_StudentKey.ToString(),
                                int.Parse(loginfo.Properties.Training_Subject_ClassKey.ToString()),
                                int.Parse(loginfo.Properties.Training_ScoreTypeKey.ToString()));
                            if (scoreinfo.Properties.Training_Subject_ClassKey > 0)
                            {
                                try
                                {
                                    dlg = new DevExpress.Utils.WaitDialogForm(MsgConfig.MSG_WAIT, MsgConfig.MSG_LOADING);
                                    // Cập nhật cột điểm vừa thay đổi
                                    scoreinfo.Properties.Score = loginfo.Properties.NewScore;
                                    scoreinfo.Save();

                                    // Lấy danh sách các loại điểm
                                    DataTable m_tblScoreType = new DataTable();
                                    m_tblScoreType = (m_data.m_DCReadOnly.Training_Scores.GetListScoreType(m_data.m_DCReadOnly.Training_SubjectClass_ScoreTypes, loginfo.Properties.Training_StudentKey.ToString(),
                                        int.Parse(loginfo.Properties.Training_Subject_ClassKey.ToString()))).ToDataTable();
                                    if (m_tblScoreType.Rows.Count != 0)
                                    {
                                        // Kiểm tra độ chênh lệch điểm cũ
                                        Double m_difference = 0;
                                        Training_Student_Subject_ClassInfo subclassInfo = new Training_Student_Subject_ClassInfo(loginfo.Properties.Training_StudentKey.ToString(),
                                            int.Parse(loginfo.Properties.Training_Subject_ClassKey.ToString()));
                                        if (subclassInfo.Properties.Training_Subject_ClassKey > 0)
                                            m_difference = Convert.ToDouble(subclassInfo.Properties.AverageScoreFinal) - Convert.ToDouble(subclassInfo.Properties.AverageScore);

                                        // Tính điểm vừa chỉnh sửa
                                        for (int i = 0; i < m_tblScoreType.Rows.Count; i++)
                                        {
                                            if ((int.Parse(m_tblScoreType.Rows[i]["Training_ScoreTypeKey"].ToString()) == 3) && (GetValueLookUpEdit.ConvertValueToInt(m_tblScoreType.Rows[i]["Score"]) > 0))
                                            {
                                                // Xóa cột điểm lần 1 khi có cột điểm lần 2
                                                for (int j = 0; j < m_tblScoreType.Rows.Count; j++)
                                                {
                                                    if (int.Parse(m_tblScoreType.Rows[j]["Training_ScoreTypeKey"].ToString()) == 2)
                                                    {
                                                        m_tblScoreType.Rows.RemoveAt(j);
                                                        break;
                                                    }
                                                }
                                                break;
                                            }
                                        }

                                        double m_score = 0;
                                        // Tính điểm
                                        for (int i = 0; i < m_tblScoreType.Rows.Count; i++)
                                        {
                                            try { m_score = m_score + (Convert.ToDouble(m_tblScoreType.Rows[i]["Score"]) * int.Parse(m_tblScoreType.Rows[i]["DefaultPercent"].ToString())) / 100; }
                                            catch { continue; }
                                        }
                                        // Làm tròn 1 số
                                        m_score = Math.Round(m_score, 2);

                                        double m_scoreFinal = m_score;
                                        // Kiểm tra điểm vừa chỉnh sửa để cộng thêm nếu có điểm cộng
                                        if ((m_difference > 0) && (m_score + m_difference <= 10))
                                            m_scoreFinal = m_score + m_difference;

                                        // Cập nhật điểm trung bình
                                        subclassInfo = new Training_Student_Subject_ClassInfo(loginfo.Properties.Training_StudentKey.ToString(),
                                            int.Parse(loginfo.Properties.Training_Subject_ClassKey.ToString()));
                                        if (subclassInfo.Properties.Training_Subject_ClassKey > 0)
                                        {
                                            subclassInfo.Properties.AverageScore = m_score;
                                            subclassInfo.Properties.AverageScoreFinal = m_scoreFinal;
                                            subclassInfo.Save();
                                        }

                                        // Cập nhật điểm trung bình tích lũy

                                        DataTable _dtListScore = new DataTable();
                                        _dtListScore = m_data.m_DCReadOnly.Training_Scores.GetSubjectScoreListofStudentByID(
                                            m_data.m_DCReadOnly.Training_Subjects,
                                            m_data.m_DCReadOnly.Training_TrainingProgram_Details,
                                            m_data.m_DCReadOnly.Training_Student_Subject_Classes,
                                            m_data.m_DCReadOnly.Training_Subject_Classes,
                                            m_data.m_DCReadOnly.Training_Students,
                                            m_data.m_DCReadOnly.Training_Student_Classes,
                                            m_data.m_DCReadOnly.Catalogue_Terms,
                                            m_data.m_DCReadOnly.Catalogue_SchoolYears,
                                            scoreinfo.Properties.Training_StudentID, -1, -1, int.Parse(loginfo.Properties.Training_TrainingProgramKey.ToString())).ToDataTable();
                                        caculateAverageScoreAccumulate(_dtListScore, scoreinfo.Properties.Training_StudentID);

                                        dlg.Close();
                                        XtraMessageBox.Show("Đã cập nhật điểm", "Thông báo");
                                    }
                                }
                                catch
                                {
                                    XtraMessageBox.Show("Không thể cập nhật dữ liệu", "Thông báo");
                                }
                            }
                            //else
                            //{
                            //    XtraMessageBox.Show("Không thể cập nhật điểm");
                            //}

                            e.Cancel = true;
                            return;
                        }
                        else
                        {
                            e.Cancel = true;
                            return;
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("Phiếu " + m_strID + " đã duyệt. Không thể chỉnh sửa");
                        e.Cancel = true;
                        return;
                    }
                }

            }

            if (this.grvView.FocusedColumn == gclRefuse)
            {
                m_iLog_ScoreEditKey = int.Parse(this.grvView.GetRowCellValue(this.grvView.FocusedRowHandle, "Log_ScoreEditKey").ToString());
                ShowInfomation(m_iLog_ScoreEditKey);
                Log_ScoreEditInfo loginfo = new Log_ScoreEditInfo(m_iLog_ScoreEditKey);
                if (loginfo.Properties.Log_ScoreEditKey > 0)
                {
                    GetValues(m_iLog_ScoreEditKey);
                    if (loginfo.Properties.Status.Value == false)
                    {
                        if (rtbFeedback.Text != "")
                        {
                            DialogResult result = XtraMessageBox.Show("Bạn không muốn phê duyệt phiếu " + m_strID, "Thông báo", MessageBoxButtons.YesNo);
                            if (result == DialogResult.Yes)
                            {
                                m_bRefuseValue = (bool)this.grvView.GetFocusedRowCellValue(gclRefuse);
                                this.grvView.SetFocusedRowCellValue(gclRefuse, !m_bRefuseValue);

                                // update
                                if (rtbFeedback.Text != "")
                                    loginfo.Properties.Feedback = rtbFeedback.Text;

                                loginfo.Properties.Refuse = true;
                                loginfo.Properties.Status = true;
                                loginfo.Properties.AccountCensorship = Utils.LoginInfo.GblLoginInfo.sysLoginUserKey;
                                loginfo.Properties.DateCensorship = SysDateTime.Now;
                                loginfo.Save();

                                e.Cancel = true;
                                return;
                            }
                            else
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                        else
                        {
                            Frm_Score2_EditScoreCensorship_Confirm confirm = new Frm_Score2_EditScoreCensorship_Confirm(loginfo);
                            confirm.ShowDialog();
                            if (Log_ScoreEditData.m_bFlag)
                            {
                                this.grvView.SetFocusedRowCellValue(gclRefuse, true);
                                e.Cancel = true;
                                return;
                            }
                            else
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("Phiếu " + m_strID + " đã duyệt. Không thể chỉnh sửa");
                        e.Cancel = true;
                        return;
                    }
                }
            }
        }

        /// <summary>
        /// Tắt form kiểm duyệt phiếu yêu cầu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult result;
            result = XtraMessageBox.Show("Bạn muốn tắt phiếu duyệt điểm ?", "Thông báo", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                this.Close();
            }
        }

        /// <summary>
        /// Chọn 1 phiếu yêu cầu để kiểm duyệt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void gctView_Click(object sender, EventArgs e)
        {
            if (!grvView.IsFilterRow(grvView.FocusedRowHandle))
            {
                m_iLog_ScoreEditKey = int.Parse(this.grvView.GetRowCellValue(this.grvView.FocusedRowHandle, "Log_ScoreEditKey").ToString());
                ShowInfomation(m_iLog_ScoreEditKey);
            }
        }

        private void caculateAverageScoreAccumulate(DataTable dtInfo, string strStudentID)
        {
            DataTable _dtScore = dtInfo;
            string _strStudentId = strStudentID;
            _dtScore.Columns.Add("HPTC");
            double _dCreditAcc = 0;
            double _dScoreAcc = 0;
            double _dCredit = 0;
            double _dScore = 0;
            for (int i = 0; i < _dtScore.Rows.Count; i++)
            {
                _dtScore.Rows[i]["HPTC"] = Convert.ToDouble(_dtScore.Rows[i]["AverageScoreFinal"].ToString()) *
                                        Convert.ToDouble(_dtScore.Rows[i]["TotalCredits"].ToString());
                if (Convert.ToDouble(_dtScore.Rows[i]["AverageScoreFinal"].ToString()) >= DefaultConfig.MinScorePass_NoYearly)
                {
                    _dCreditAcc += Convert.ToDouble(_dtScore.Rows[i]["TotalCredits"].ToString());
                    _dScoreAcc += Convert.ToDouble(_dtScore.Rows[i]["HPTC"].ToString());
                }
                _dCredit += Convert.ToDouble(_dtScore.Rows[i]["TotalCredits"].ToString());
                _dScore += Convert.ToDouble(_dtScore.Rows[i]["HPTC"].ToString());
            }
            double averageScoreAcc = 0;
            if (_dScoreAcc != 0)
            {
                averageScoreAcc = Math.Round(_dScoreAcc / _dCreditAcc, 2, MidpointRounding.AwayFromZero);
            }
            double averageScore = 0;
            if (_dScore != 0)
            {
                averageScore = Math.Round(_dScore / _dCredit, 2, MidpointRounding.AwayFromZero);
            }
            Training_Student_ClassInfo infoStudentClass = new Training_Student_ClassInfo(_strStudentId);
            infoStudentClass.Properties.AverageScoreAccumulate = averageScoreAcc;
            infoStudentClass.Properties.AverageScoreNoAccumulate = averageScore;
            infoStudentClass.Properties.TotalCreditAccumulate = _dCreditAcc;
            infoStudentClass.Save();
        }
    }
}
